﻿using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace TouchSocketServer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Button_Click();
        }

        private void Button_Click()
        {
            var service = new TcpService();
            service.Connecting = (client, e) =>
            {
                client.SetDataHandlingAdapter(new FixedHeaderPackageAdapter() { FixedHeaderType = FixedHeaderType.Int });
            };//有客户端正在连接
            service.Connected = (client, e) => { string s = client.IP; };//有客户端成功连接
            service.Disconnecting = (client, e) => { string s = client.IP; };//有客户端正在断开连接，只有当主动断开时才有效。
            service.Disconnected = (client, e) => { MessageBox.Show("掉线"); };//有客户端断开连接
            List<byte> res = new List<byte>();
            List<byte> res1 = new List<byte>();
            int i = 0;
            int size = 0;
            service.Received = (client, e, r) =>
            {
                //从客户端收到信息
                byte[] buffer = e.Buffer;

                Image l = buffer[0] switch
                {
                    0 => list,
                    1 => list1,
                    2 => list2,
                    3 => list3,
                    _=>null 
                };

                //var mes = Encoding.UTF8.GetString(e.Buffer, 1, e.Len);//注意：数据长度是Len
                //res.AddRange(buffer);
                //client.Logger.Info($"已从{client.ID}接收到信息：{mes}");
                //client.Send(mes);//将收到的信息直接返回给发送方
                using (MemoryStream ms = new MemoryStream(buffer.Skip(1).ToArray()))
                {
                    //using (Stream s= File.Create("1.jpg"))
                    //{
                    //    ms.CopyTo(s);
                    //}
                    this.Dispatcher.Invoke(() =>
                    {
                        BitmapImage b = new BitmapImage();
                        b.BeginInit();
                        b.CacheOption = BitmapCacheOption.OnLoad;
                        b.StreamSource = ms;
                        b.EndInit();
                        l.Source = b;
                    });
                }



                //client.Send("id",mes);//将收到的信息返回给特定ID的客户端

                //将收到的信息返回给在线的所有客户端。
                //注意：这里只是一个建议思路，实际上群发应该使用生产者消费者模式设计
                //var ids = service.GetIds();
                //foreach (var clientId in ids)
                //{
                //    if (clientId != client.Id)//不给自己发
                //    {
                //        service.Send(clientId, mes);
                //    }
                //}

            };

            service.Setup(new TouchSocketConfig()//载入配置
                .SetListenIPHosts(new IPHost[] { new IPHost(55555) })//同时监听两个地址
                .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                {
                    a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                })
                .ConfigurePlugins(a =>
                {
                    //a.Add();//此处可以添加插件
                }));

            service.Start();//启动

        }


    }
}